package com.wcs.exam.common.util;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wcs
 */
@Slf4j
public final class EnumUtil {
    private EnumUtil() {
    }

    public static final String DEFAULT_PREFIX = "com.wcs.exam.common.enums.";

    private static final String DEFAULT_ENUM_NAME = "name";

    /**
     * 枚举转List格式
     *
     * @param targetEnumClazz 目标枚举Clazz
     * @return 转换结果
     */
    public static List<Map<String, Object>> toList(Class<?> targetEnumClazz) {
        try {
            //获取方法
            Method[] methods = targetEnumClazz.getMethods();
            Field[] fields = targetEnumClazz.getDeclaredFields();
            List<Field> fieldList = new ArrayList<>();
            for (Method method : methods) {
                for (Field field : fields) {
                    if (method.getName().endsWith(toUpperCaseFirstOne(field.getName()))) {
                        fieldList.add(field);
                    }
                }
            }

            List<Map<String, Object>> resultList = new ArrayList<>();
            //获取值
            Enum<?>[] enums = (Enum<?>[]) targetEnumClazz.getEnumConstants();
            for (Enum<?> e : enums) {
                Map<String, Object> eMap = new HashMap<>();
                StringBuilder enumNameValue = new StringBuilder(e.name());
                for (Field field : fieldList) {
                    field.setAccessible(true);
                    if (field.getName().equals(DEFAULT_ENUM_NAME)) {
                        enumNameValue.append(";").append(field.get(e));
                    } else {
                        eMap.put(field.getName(), field.get(e));
                    }
                }
                if (enumNameValue.toString().startsWith(";")) {
                    enumNameValue = new StringBuilder(enumNameValue.substring(1));
                }
                eMap.put(DEFAULT_ENUM_NAME, enumNameValue.toString());
                resultList.add(eMap);
            }

            return resultList;
        } catch (RuntimeException | IllegalAccessException e) {
            log.error("系统异常", e);
        }
        return null;
    }

    /**
     * 首字母转大写
     *
     * @param s 需要操作的字符串
     * @return 转换后结果
     */
    private static String toUpperCaseFirstOne(String s) {
        if (Character.isUpperCase(s.charAt(0))) {
            return s;
        } else {
            return Character.toUpperCase(s.charAt(0)) + s.substring(1);
        }
    }

}
